using System;
using System.Net.Sockets;
using QFramework;
using QGameFramework;
using UnityEngine;

public class TCPClient : BaseComponent
{
    private Socket client;

    private byte[] readBuff = new byte[1024];
    string recvStr = String.Empty;

    private string ipAds;
    private int port;

    private void Start()
    {
        InvokeRepeating("TryConnect", 0, 1);
    }

    public void OnConnectedToServer(string gameConfigIpAdr, int gameConfigPort)
    {
        ipAds = gameConfigIpAdr;
        port = gameConfigPort;
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.BeginConnect(gameConfigIpAdr, gameConfigPort, ConnectCallback, client);
    }

    private void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            Socket socket = (Socket)ar.AsyncState;
            socket.EndConnect(ar);
            Debug.Log("Socket Connect Succ");
            socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);
        }
        catch (SocketException ex)
        {
            Debug.Log("Socket Connect fail" + ex.ToString());
        }
    }

    private void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            Socket socket = (Socket)ar.AsyncState;
            int count = socket.EndReceive(ar);
            recvStr = System.Text.Encoding.Default.GetString(readBuff, 0, count);
            LogKit.I($"接收到服务器的消息：{recvStr}");
            socket.BeginReceive(readBuff, 0, 1024, 0,
                ReceiveCallback, socket);
        }
        catch (SocketException ex)
        {
            Debug.Log("Socket Receive fail" + ex.ToString());
        }
    }

    public void Send(string msg)
    {
        if (client.Connected)
        {
            byte[] sendBytes =
                System.Text.Encoding.Default.GetBytes(msg);
            client.Send(sendBytes);
        }
        else
        {
            TryConnect();
        }
    }

    public void Send(byte[] sendBytes)
    {
        if (client.Connected)
        {
            client.Send(sendBytes);
        }
        else
        {
            TryConnect();
        }
    }

    private void TryConnect()
    {
        if (!client.Connected)
        {
            OnConnectedToServer(ipAds, port);
        }
    }
}